<template>
  <common-list>
    <el-form
      slot="search"
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="规则名称" prop="ruleName">
        <common-input
          :verify="false"
          v-model="queryParams.ruleName"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="handleQuery"
          v-hasPermi="['apisecurity:sensitiverule:query']"
          >查询
        </el-button>
        <el-button
          icon="el-icon-refresh"
          @click="resetQuery"
          v-hasPermi="['apisecurity:sensitiverule:query']"
          >重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" slot="tools">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['apisecurity:sensitiverule:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          v-hasPermi="['apisecurity:sensitiverule:add']"
          @click="handleDelete"
          :disabled="!showBatch"
          >批量删除
        </el-button>
      </el-col>
    </el-row>

    <common-table
      slot="content"
      v-loading="loading"
      :data="ruleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="规则名称"
        align="left"
        prop="ruleName"
        show-overflow-tooltip
      />
      <el-table-column label="匹配规则" align="left" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.reg }}
        </template>
      </el-table-column>
      <el-table-column label="替换正则" align="left" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.replaceReg }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status == 0">启用</el-tag>
          <el-tag type="danger" v-else-if="scope.row.status == 1">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="180px">
        <template slot-scope="scope">
          <el-button type="text" @click="getRule(scope.row, 2)"
            >详情
          </el-button>
          <el-button
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['apisecurity:sensitiverule:edit']"
            >编辑
          </el-button>
          <el-button
            type="text"
            @click="handleUpdateStatus(scope.row)"
            v-hasPermi="['apisecurity:sensitiverule:status']"
          >
            <span v-if="scope.row.status == 1">启用</span>
            <span v-if="scope.row.status == 0">停用</span>
          </el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['apisecurity:sensitiverule:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或编辑敏感规则对话框 -->
    <common-edit-dialog
      :title="title"
      :visible.sync="open"
      @cancel="cancel"
      @submit="submitForm"
      class="dataTypeDialog"
      :buttonLoading="buttonLoading"
    >
      <!-- <el-form ref="form" :model="form" :rules="rules" label-width="100px"> -->
      <el-form
        ref="formTop"
        :model="formTop"
        :rules="rulesTop"
        label-width="100px"
      >
        <!-- <el-form-item label="id" prop="id" hidden="true">
          <common-input v-model="formTop.id" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="分组列表" prop="groupList" hidden="true">
          <common-input v-model="formTop.groupList" placeholder="请输入规则名称" />
        </el-form-item> -->
        <el-form-item label="规则名称" prop="ruleName">
          <common-input
            v-model="formTop.ruleName"
            placeholder="请输入规则名称"
          />
        </el-form-item>
        <el-form-item label="测试内容" prop="testContent">
          <common-input
            :verify="false"
            v-model="formTop.testContent"
            placeholder="多个测试内容用逗号隔开"
          />
        </el-form-item>
        <el-form-item label="匹配正则" prop="reg">
          <common-input
            :verify="false"
            v-model="formTop.reg"
            type="textarea"
            :maxlength="1500"
            placeholder="请输入"
          />
          <el-button
            class="titleBtnPlace"
            type="primary"
            plain
            @click="matchReg()"
            >匹配
          </el-button>
        </el-form-item>
        <el-form-item label="匹配结果" prop="matchingResult">
          <common-input
            :verify="false"
            v-model="formTop.matchingResult"
            disabled
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>

      <el-form
        ref="formCenter"
        :model="formCenter"
        :rules="rulesCenter"
        label-width="100px"
      >
        <el-form-item label="替换方式" prop="replaceMode">
          <el-radio-group
            v-model="formCenter.replaceMode"
            @change="replaceResultPage"
          >
            <el-radio :label="0">默认</el-radio>
            <el-radio :label="1">分组替换</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="替换正则" prop="replaceReg" v-if="showInput === 0">
          <common-input
            :verify="false"
            v-model="formCenter.replaceReg"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
          />
          <el-button
            class="titleBtnPlace"
            type="primary"
            plain
            @click="replaceReg()"
            >替换
          </el-button>
        </el-form-item>

        <el-form-item label="分组正则" prop="replaceReg" v-if="showInput === 1">
          <common-input
            :verify="false"
            v-model="formCenter.replaceReg"
            type="textarea"
            :rows="3"
            placeholder="请输入分组正则"
          />
          <el-button
            class="titleBtnPlace"
            type="primary"
            @click="classReg()"
            plain
            >分组
          </el-button>
        </el-form-item>
      </el-form>

      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item
          label="分组结果"
          prop="groupResult"
          v-if="showInput === 1"
        >
          <div class="groupResultArr">
            <el-checkbox-group v-model="form.groupList">
              <el-checkbox
                v-for="(v, i) in groupResultArr"
                :key="i"
                :label="i + 1"
                >{{ v }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <el-button
            class="titleBtnPlace"
            type="primary"
            plain
            @click="replaceReg()"
            >替换
          </el-button>
        </el-form-item>
        <el-form-item label="替换结果" prop="replaceResult">
          <common-input
            :verify="false"
            disabled
            v-model="form.replaceResult"
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <common-input
            :verify="false"
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">启用</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
    </common-edit-dialog>

    <!-- 详情 -->
    <common-info-dialog
      :title="detailsTitle"
      :visible.sync="detailsOpen"
      @cancel="cancel"
    >
      <common-info-table>
        <common-info-table-cell label="规则名称" width="50%"
          >{{ form.ruleName }}
        </common-info-table-cell>
        <common-info-table-cell label="状态" width="50%">
          {{ form.status === 0 ? "启用" : form.status === 1 ? "停用" : "" }}
        </common-info-table-cell>

        <common-info-table-cell label="匹配结果" width="50%"
          >{{ form.matchingResult }}
        </common-info-table-cell>
        <common-info-table-cell label="替换方式" width="50%">
          {{
            form.replaceMode == 0
              ? "默认"
              : form.replaceMode == 1
              ? "分组替换"
              : ""
          }}
        </common-info-table-cell>
        <common-info-table-cell label="测试内容"
          >{{ form.testContent }}
        </common-info-table-cell>
        <common-info-table-cell label="分组正则"
          >{{ form.replaceReg }}
        </common-info-table-cell>
        <common-info-table-cell label="分组结果"
          >{{ form.groupResult }}
        </common-info-table-cell>
        <common-info-table-cell label="替换结果"
          >{{ form.replaceResult }}
        </common-info-table-cell>
        <common-info-table-cell label="备注"
          >{{ form.remark }}
        </common-info-table-cell>
        <common-info-table-cell label="创建时间"
          >{{ form.createTime }}
        </common-info-table-cell>
        <common-info-table-cell label="匹配规则"
          >{{ form.reg }}
        </common-info-table-cell>
      </common-info-table>
    </common-info-dialog>
  </common-list>
</template>

<script>
import {
  listRule,
  getRule,
  delRule,
  addRule,
  updateRule,
  matchRule,
  replaceRule,
  classRule,
  updateRuleStatus,
} from "@/api/apisecurity/sensitiverule/rule";
import { getDicts } from "@/api/system/dict/data";
import { regExpRule } from "@/utils/formRules";
import BaseList from "@/mixins/BaseList";
import errorCode from "@/utils/errorCode";

export default {
  name: "Rule",
  mixins: [BaseList],
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示查询条件
      showSearch: true,
      // 总条数
      total: 0,
      // 敏感规则表格数据
      ruleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      detailsOpen: false,
      detailsTitle: "",
      // 状态数据字典
      statusOptions: [],
      //展示和隐藏input
      showInput: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: undefined,
      },
      groupResultArr: [],
      // 表单参数
      form: {},
      buttonLoading: false,
      formTop: {},
      formCenter: {},
      // 表单校验
      rules: {
        remark: [{ max: 256, message: "长度不能超过256", trigger: "blur" }],

        // matchingResult: [
        //   { required: true, message: "匹配结果不能为空", trigger: "blur" },
        // ],
        // replaceMode: [
        //   { required: true, message: "替换方式不能为空", trigger: "blur" },
        // ],
        // replaceReg: [
        //   { required: true, message: "正则不能为空", trigger: "blur" },
        // ],
        status: [{ required: true, message: "请输入正则", trigger: "blur" }],
      },
      rulesTop: {
        ruleName: [
          { required: true, message: "请输入规则名称", trigger: "blur" },
        ],
        testContent: [
          { required: true, message: "请输入测试内容", trigger: "blur" },
        ],
        reg: { required: true, message: "请输入匹配正则", trigger: "blur" },
        // regExpRule
      },
      rulesCenter: {
        replaceMode: [
          { required: true, message: "请选择替换方式", trigger: "blur" },
        ],
        replaceReg: [
          { required: true, message: "请输入正则", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then((res) => {
      this.statusOptions = res.data;
    });
  },
  methods: {
    /** 分组页面替换 */
    replaceResultPage() {
      if (this.formCenter.replaceMode == 0) {
        this.showInput = 0;
      } else {
        //显示 分组替换内容
        this.showInput = 1;
        this.$set(this.form, "replaceResult", "");
        this.$set(this.form, "groupRegular", this.form.replaceReg);
      }
    },
    /** 匹配结果 */
    matchReg() {
      this.$refs["formTop"].validate((valid) => {
        if (valid) {
          // console.log(this.form.groupList)
          const groupList =
            this.form.groupList && this.form.groupList.length
              ? this.form.groupList.join(",")
              : "";
          const newParams = Object.assign({}, this.formTop, { groupList });
          matchRule(newParams).then((res) => {
            if (res && res.code === 200) {
              this.$set(
                this.formTop,
                "matchingResult",
                res.data.matchList.join(",")
              );
              this.$GlobalSuccessMessage("匹配成功");
            } else {
              this.$GlobalErrorConfirm("匹配失败", res.msg);
            }
          });
        }
      });
    },
    /** 替换结果 */
    replaceReg() {
      this.$refs["formCenter"].validate((valid) => {
        if (valid) {
          const groupList =
            this.form.groupList && this.form.groupList.length
              ? this.form.groupList.join(",")
              : "";
          const newParams = Object.assign(
            {},
            this.form,
            this.formTop,
            this.formCenter,
            { groupList }
          );
          replaceRule(newParams).then((res) => {
            if (res && res.code === 200) {
              this.$set(this.form, "replaceResult", res.data.list.join(","));
              this.$GlobalSuccessMessage("替换成功");
            } else {
              this.$GlobalErrorConfirm("替换失败", res.msg);
            }
          });
        }
      });
    },
    /** 分组结果 */
    classReg() {
      const params = Object.assign(
        {},
        this.form,
        this.formTop,
        this.formCenter,
        {
          groupList:
            this.form.groupList && this.form.groupList.length
              ? this.form.groupList.join(",")
              : "",
          groupResult: this.form.groupResult ? this.form.groupResult : "",
        }
      );
      classRule(params).then((res) => {
        if (res && res.code === 200) {
          let groupResult = [];
          if (res.data) {
            res.data[0].map((v, i) => {
              let arr = [];
              res.data.map((value, index) => {
                arr.push(value[i] && value[i] != null ? value[i] : null);
              });
              groupResult.push("第" + (i + 1) + "组" + arr.join(","));
            });
          }
          this.groupResultArr = groupResult;
          this.$set(this.form, "groupResult", JSON.stringify(groupResult));
          this.$set(this.form, "groupList", []);
          this.$GlobalSuccessMessage("分组成功");
        } else {
          this.$GlobalErrorConfirm("分组失败", res.msg);
        }
      });
    },
    /** 查询敏感规则列表 */
    getList() {
      this.loading = true;
      listRule(this.queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            this.ruleList = res.rows;
            this.total = res.total;
          } else {
            this.ruleList = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.detailsOpen = false;
      this.reset();
      this.resetTop();
      this.resetCenter();
      this.reParams();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        // ruleName: undefined,
        // reg: undefined,
        replaceReg: undefined,
        groupList: "",
        // testContent: undefined,
        matchingResult: undefined,
        replaceMode: 0,
        replaceResult: undefined,
        groupRegular: undefined,
        groupResult: "",
        status: 1,
        delFlag: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
      };
      this.resetForm("form");
      this.showInput = 0;
    },
    resetTop() {
      this.formTop = {
        ruleName: undefined,
        reg: undefined,
        testContent: undefined,
      };
      this.resetForm("formTop");
    },
    resetCenter() {
      this.formCenter = {
        replaceMode: 0,
        replaceReg: undefined,
      };
      this.resetForm("formCenter");
    },
    reParams() {
      this.groupResult = [];
      this.groupResultArr = [];
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.resetTop();
      this.resetCenter();
      this.reParams();
      this.open = true;
      this.title = "新增敏感规则";
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.resetTop();
      this.resetCenter();
      this.reParams();
      this.getRule(row, 1);
    },
    getRule(row, n) {
      const id = row.id || this.ids;
      getRule(id).then((res) => {
        if (res && res.code === 200) {
          this.form = Object.assign({}, res.data, {
            groupList: res.data.groupList
              ? res.data.groupList.split(",").map(Number)
              : "",
          });
          this.formTop = Object.assign(
            {},
            {
              ruleName: res.data.ruleName,
              testContent: res.data.testContent,
              reg: res.data.reg,
              matchingResult: res.data.matchingResult,
            }
          );
          this.formCenter = Object.assign(
            {},
            {
              replaceMode: res.data.replaceMode,
              replaceReg: res.data.replaceReg,
            }
          );

          if (n === 1) {
            this.showInput = parseInt(res.data.replaceMode);
            const groupResult =
              res.data.groupResult && this.isJson(res.data.groupResult)
                ? JSON.parse(res.data.groupResult)
                : [];
            this.groupResultArr = groupResult;

            this.open = true;
            this.title = "编辑敏感规则";
          } else {
            this.detailsOpen = true;
            this.detailsTitle = "敏感规则详情";
          }
        } else {
          this.$GlobalErrorConfirm("数据加载失败", res.msg);
        }
      });
    },
    isJson(str) {
      if (typeof str == "string") {
        try {
          var obj = JSON.parse(str);
          if (typeof obj == "object" && obj) {
            return true;
          } else {
            return false;
          }
        } catch (e) {
          console.log("error" + str + "!!!" + e);
          return false;
        }
      }
      console.log("It is not a string!");
    },
    /** 提交按钮 */
    submitForm() {
      const newParent = Object.assign(
        {},
        this.form,
        {
          groupList:
            this.form.groupList && this.form.groupList.length
              ? this.form.groupList.join(",")
              : "",
        },
        this.formTop,
        this.formCenter
      );
      this.$refs["formTop"].validate((valid) => {
        if (valid) {
          this.$refs["formCenter"].validate((valid) => {
            if (valid) {
              this.$refs["form"].validate((valid) => {
                if (valid) {
                  this.buttonLoading = true;
                  if (this.form.id != null) {
                    updateRule(newParent)
                      .then((res) => {
                        if (res && res.code === 200) {
                          this.$GlobalSuccessMessage("编辑成功");
                          this.open = false;
                          this.getList();
                        } else {
                          this.$GlobalErrorConfirm("编辑失败", res.msg);
                        }
                      })
                      .finally(() => {
                        this.buttonLoading = false;
                      });
                  } else {
                    addRule(newParent)
                      .then((res) => {
                        if (res && res.code === 200) {
                          this.$GlobalSuccessMessage("新增成功");
                          this.open = false;
                          this.getList();
                        } else {
                          this.$GlobalErrorConfirm("新增失败", res.msg);
                        }
                      })
                      .finally(() => {
                        this.buttonLoading = false;
                      });
                  }
                }
              });
            }
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (row && row.id) {
        if (row.status === 0) {
          return this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
        }
      } else {
        try {
          this.ids.forEach((f) => {
            if (this.ruleList.find((v) => v.id === f).status === 0) {
              throw false;
            }
          });
        } catch {
          return this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
        }

        // for (let i = 0; i < this.ids.length; i++) {
        //   for (let j = 0; j < this.ruleList.length; j++) {
        //     if (this.ids[i] === this.ruleList[j].id) {
        //       if (this.ruleList[j].status === 0) {
        //         return this.$GlobalErrorConfirm('删除失败', '启用状态下不允许删除')
        //       }
        //     }
        //   }
        // }
      }
      const ids = row.id ? row.id : this.ids.join(",");
      this.$GlobalDeleteConfirm(
        "删除敏感标识会同时删除与资产的绑定关系，是否确定删除"
      )
        .then(() => {
          delRule({ ids }).then((res) => {
            if (res && res.code == 200) {
              this.queryParams.pageNum = 1;
              this.$GlobalSuccessMessage("删除成功");
              this.getList();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },
    /** 启用停用按钮操作 */
    handleUpdateStatus(row) {
      updateRuleStatus(row).then((res) => {
        if (res && res.code == 200) {
          this.queryParams.pageNum = 1;
          this.$GlobalSuccessMessage("操作成功");
          this.getList();
        } else {
          this.$GlobalErrorConfirm("操作失败", res.msg).then();
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.groupResultArr {
  background: aliceblue;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0px 10px;
  min-height: 80px;
}

.overflowHiddenThree {
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
}

.dataTypeDialog {
  .el-form-item {
    position: relative;
  }

  .titleBtnPlace {
    margin-top: 10px;
  }
}
</style>
